Axios is a JavaScript library used to make API calls (HTTP requests) in React and JavaScript applications.
Used:
- Get data from server (GET)
- Send data to server (POST)
- Update data (PUT)
- Delete data (DELETE)
npm install axiosImport Axios:
import axios from "axios";
import { useEffect, useState } from "react";Fetch Data:
function App() {
const [data, setData] = useState([]);
useEffect(() => {
axios.get("https://tutorialsonweb.com/users")
.then(response => {
setData(response.data);
})
.catch(error => {
console.log(error);
});
}, []);
return (
<div>
<h1>User List</h1>
{data.map(user => (
<p key={user.id}>{user.name}</p>
))}
</div>
);
}
export default App;POST:
axios.post("https://tutorialsonweb.com/users", {
name: "John",
age: 25
})
.then(response => {
console.log(response.data);
});PUT:
axios.put("https://tutorialsonweb.com/users/1", {
name: "Updated Name"
});Delete:
axios.delete("https://tutorialsonweb.com/users/1");